//mui.init({
//	beforeback: function() {
//		return true;
//	}
//});
var imgNumber = 0;
var divSelectImg = mui("#div_selectImg")[0]; //添加图片的框框
mui.init({
	beforeback: function() {
		var parent = plus.webview.currentWebview().opener();
		//触发列表界面的自定义事件（reloadMethod）,从而进行数据刷新  
		mui.fire(parent, 'reloadView');
		//返回true，继续页面关闭逻辑
		return true;
	}
});
//用于图片
var WORDS_NUM = 160;
var NAME_LENGTH = 100;
mui.init();
var persId;
var persName;
var timer = null;
var currentType = "默认事件";
var currentTypecode = "10001";

//获取数据
var speechOptiion = { //语音识别配置
	engine: 'iFly', //语音引擎
	punctuation: false, //不要标点符号
	timeout: 20000, //语音识别超时时间
	continue: false //是否20000采用持续模式
};

var eventT = [{
	"text": "默认事件",
	"value": "10001"
}, {
	"text": "预警事件",
	"value": "10002"
}]
mui.plusReady(function() {
	initData();
	mui.previewImage();
	initListener();

});

function initData() {
	var currentTime = getCurDate();
	$("#eventType").find("a span").html(currentType);
	$("#eventType").attr("data", currentTypecode);
	persId = getUserModel().persId;
	persName = getUserModel().persName;
	$("#eventLoginName").find("a span").html(persName);
	$("#eventLoginName").attr("data", persId);
	$("#eventTime").find("a span").html(currentTime);
}

/*
 * 获取当前时间并格式化
 */
function getCurDate() {
	var now = new Date();
	var year = now.getFullYear();
	var month = now.getMonth() + 1;
	if(month < 10) {
		month = '0' + month;
	}
	var date = now.getDate();
	if(date < 10) {
		date = '0' + date;
	}
	var hour = now.getHours();
	if(hour < 10) {
		hour = '0' + hour;
	}
	var minute = now.getMinutes();
	if(minute < 10) {
		minute = '0' + minute;
	}
	var second = now.getSeconds();
	if(second < 10) {
		second = '0' + second;

	}
	return year + "-" + month + "-" + date + " " + hour + ":" + minute
}

function initListener() {

	// 加载图片预览功能
	// 设置底部栏位置，防止软键盘弹出时被顶上来
	if(window.innerWidth > 500) {
		mui("#div_bottomCancel")[0].style.top = (window.innerHeight - 0.96 * window.innerWidth / (7.2 * 1.5)) + "px";
		mui("#div_bottomSave")[0].style.top = (window.innerHeight - 0.96 * window.innerWidth / (7.2 * 1.5)) + "px";
	} else {
		mui("#div_bottomSave")[0].style.top = (window.innerHeight - 0.96 * window.innerWidth / 7.2) + "px";
		mui("#div_bottomCancel")[0].style.top = (window.innerHeight - 0.96 * window.innerWidth / 7.2) + "px";
	}
	/*
	 * 给发现日期添加事件
	 * 
	 */
	var optionsJson = document.getElementById("eventTime").getAttribute('data-options') || '{}';
	var options = JSON.parse(optionsJson);
	$("#eventTime").on("tap", function() {
		var picker = new mui.DtPicker(options);
		picker.show(function(rs) {
			$("#eventTime").find("a span").html(rs.text)
			$("#eventTime").attr("data", rs.text);
			picker.dispose();
		});
	});

	/*
	 * 选择事件类型 eventType
	 */

	$("#eventType").on("tap", function() {
		var TypePicker = new mui.PopPicker();
		TypePicker.setData(eventT);
		TypePicker.show(function(items) {
			if(items[0].text != undefined) {
				$("#eventType").find("a span").html(items[0].text);
				$("#eventType").attr("data", items[0].value);
			}
		});
	});

	//手写描述
	mui("#textarea_text")[0].addEventListener("input", function() {
		if(mui.os.ios) {
			var count = this.value.split('\n').length - 1; //获取回车的个数
			mui("#span_textNumber")[0].innerText = this.value.length + count || 0;
		} else {
			mui("#span_textNumber")[0].innerText = this.value.length;
		}
	});
	//手写备注
	mui("#textarea_text_bz")[0].addEventListener("input", function() {
		if(mui.os.ios) {
			var count = this.value.split('\n').length - 1; //获取回车的个数
			mui("#span_textNumber_bz")[0].innerText = this.value.length + count || 0;
		} else {
			mui("#span_textNumber_bz")[0].innerText = this.value.length;
		}
	});

	$("#div_bottomCancel").on("tap", function() {
		mui.back();
	});
	$("#div_bottomSave").on("tap", function() {
		var fileNames = "";
		//先上传图片到ftp上面
		mui.each(mui("#div_imgLine img"), function(i, item) {
			if(!item.getAttribute("imgID")) {
				var strs = item.src.split("/");
				console.log("item.path " + item.path);
				if(fileNames != "") {
					fileNames += "*";
				}
				fileNames += strs[strs.length - 1];
			}
		});
		var params = {
			"qxid": "NONE",
			"wjmc": fileNames
		}
		/*
		 * 校验必传字段你 
		 */
		if($("#btitle").val() == "") {
			mui.toast("请输入标题")
			rerurn;
		} else if($("#textarea_text").val() == "") {
			mui.toast("请输入问题描述")
			rerurn;
		}

		var tpCount = mui("#div_imgLine img").length;
		plus.nativeUI.showWaiting();
		if(tpCount > 0 && getNetState()) {
			//上传附件
			uploadFj(params, function(fjid) {
				//上传缺陷
				uploadData(fjid);
			}, function() {});
		} else {
			uploadData();
		}

	});

	//添加图片
	mui("#div_selectImg")[0].addEventListener("tap", function() {
		PickImage(true, function(srcArray) { //该方法会返回装有所选图片的地址的数组，第一个参数是是否多图片选择，第二个是成功回调
			mui.each(srcArray, function(i, item) {
				showImg(item); //展示所选图片
			})
		})
	});
	//删除照片
	mui("#div_imgLine").on("tap", ".div_delete_img", function() {
		var _this = this;
		imgNumber--;
		mui("#div_imgLine")[0].removeChild(_this.parentNode);
		if(imgNumber < 9) {
			mui("#div_imgLine")[0].appendChild(divSelectImg);
		}
	});

}

$(function() {
	// 为每一个textarea绑定事件使其高度自适应
	$.each($("textarea"), function(i, n) {
		autoTextarea($(n)[0]);
	});
})

/**
 * 获取网络状态
 */
function getNetState() {
	var network = plus.networkinfo.getCurrentType();
	if(network == plus.networkinfo.CONNECTION_WIFI ||
		network == plus.networkinfo.CONNECTION_ETHERNET ||
		network == plus.networkinfo.CONNECTION_CELL2G ||
		network == plus.networkinfo.CONNECTION_CELL3G ||
		network == plus.networkinfo.CONNECTION_CELL4G) {
		return true;
	} else {
		return false;
	}
}

//网络状态改变监听
function onNetChange() {　　 // 获取当前网络类型
	var nt = plus.networkinfo.getCurrentType();　　
	switch(nt) {　　　　
		case plus.networkinfo.CONNECTION_ETHERNET:
		case plus.networkinfo.CONNECTION_WIFI:
		case plus.networkinfo.CONNECTION_CELL2G:
		case plus.networkinfo.CONNECTION_CELL3G:
		case plus.networkinfo.CONNECTION_CELL4G:
			//			mui(".net_unavailable")[0].classList.add("mui-hidden");　
			break;　　　　
		default:
			//			mui('.net_unavailable')[0].classList.remove("mui-hidden");　　　　　
			break;　　
	}
}

/**
 * 上传文件
 */

function uploadFj(mParams, success, error) {
	console.log('请求地址' + SERVER_ADDRESS + '请求参数' + JSON.stringify(mParams));
	var task = plus.uploader.createUpload(SERVER_ADDRESS + "/sdxsms/sdxsMissionPageController/fjsc.do", {
		method: "POST"
	}, function(t, status) {
		// 上传完成
		var responseText = JSON.parse(t.responseText);
		if(status == 200) {
			plus.nativeUI.closeWaiting();
			if(responseText.successful == "true") {
				var objIdArr = JSON.parse(t.responseText).resultValue.QXGUID;
				success(objIdArr);
			}
		} else {
			plus.nativeUI.closeWaiting();
			error();
		}
	});
	//  是否有需要上传的文件或图片
	mui.each(mui("#div_imgLine img"), function(i, item) {
		if(!item.getAttribute("imgID")) {
			task.addFile(item.path, {
				key: "wjl" + i
			});
		}
	});
	task.addData("params", JSON.stringify(mParams));
	task.start();
}

function uploadData(qxguid) {
	var netState = 0;
	var params = {
		sjlx: $("#eventType").attr("data") || "",
		persId: persId,
		qxguid: qxguid || 'NONE',
		btitle: $("#btitle").val(),
		dtime: $("#eventTime").find("a span").html(),
		bz: $("#textarea_text_bz").val(),
		wtms: $("#textarea_text").val()
	}
	var PROCESS_CREATSEND = '/sdxsms/sdxsMissionPageController/tjqx.do'; //需要上传的接口地址
	ajaxF1(PROCESS_CREATSEND, params, function(data) {
		plus.nativeUI.closeWaiting();
		if(data.successful) {
			mui.toast("成功");
			mui.back();
		} else {
			mui.toast(data.resultHint);
		}
	}, function() {
		mui.toast("网络请求失败");
		plus.nativeUI.closeWaiting();
	});

}

/**
 * 显示图片
 * 
 * @param {Object}
 *            url
 * @param {Object}
 *            imgID
 */

function showImg(url, imgID) {
	var nowTime = Date.parse(new Date()).toString(); // 时间戳
	var divImgLine = mui("#div_imgLine")[0];
	var divImgContainer = document.createElement('div');
	divImgContainer.className = "div_img_container";
	var divDeleteImg = document.createElement('div');
	divDeleteImg.className = "div_delete_img";
	divDeleteImg.innerHTML = '<span class="icon-wrong"></span>';
	var img = document.createElement('img');
	img.src = url;
	img.setAttribute("data-preview-src", "");
	img.setAttribute("data-preview-group", "1");
	if(imgID) {
		img.setAttribute("imgID", imgID);
	}
	img.onload = function() {
		if(!imgID) {
			plus.io.resolveLocalFileSystemURL(url, function(entry) {
				entry.file(function(file) {
					console.log(img.offsetHeight + "," + img.offsetWidth)
					if(img.offsetHeight > img.offsetWidth) {
						img.style.height = "auto";
						img.style.width = "100%";
					} else {
						img.style.height = "100%";
						img.style.width = "auto";
					}
					img.className = "img_style";
					img.fileName = file.name;
					var url2 = url.substr(0, url.lastIndexOf("/")) + "/" + nowTime + file.name; // 压缩成功后的图片地址
					plus.zip.compressImage({
						src: url,
						dst: url2,
						quality: 20,
						overwrite: true, // 压缩后的图片是否覆盖压缩前的图片
					}, function(event) {
						img.onload = function() {};
						img.src = url2;
						img.path = url2;
					}, function(error) {
						img.onload = function() {};
						img.src = url;
						img.path = url;
						console.log("图片压缩失败，将上传原图片");
					});
				});
			}, function(e) {
				console.log(e.message);
			});
		} else {
			console.log(img.height + "," + img.width)
			if(img.height > img.width) {
				img.style.height = "auto";
				img.style.width = "100%";
			} else {
				img.style.height = "100%";
				img.style.width = "auto";
			}
			img.className = "img_style";
		}
		if(divImgLine.children.length > imgNumber) {
			divImgLine.removeChild(divSelectImg);
		}
		divImgContainer.appendChild(img);
		divImgContainer.appendChild(divDeleteImg);
		divImgLine.appendChild(divImgContainer);
		imgNumber++;
		if(imgNumber < 9) {
			divImgLine.appendChild(divSelectImg);
		}
		console.log(divImgLine.children.length + "," + imgNumber);
	}
};